package net.homelinux.chaoswg.io.renga.krypto.animations.Xor;

import java.awt.GridLayout;
import java.util.Observable;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.BevelBorder;

import net.homelinux.chaoswg.io.renga.core.registries.GlobalPropertyRegistry;
import net.homelinux.chaoswg.io.renga.krypto.operations.vector.Xor;

public class XorStateChanger extends Observable implements Runnable {
    final XorState initialState;

    JLabel firstOperandsDisplay;
    JLabel secondOperandsDisplay;
    JLabel resultDisplay;
    JFrame jw;


    public XorStateChanger (XorState initialState) {
        this.initialState = initialState;

        jw = new JFrame ("Xor");
        jw.getContentPane().add(getPanel());
        jw.setLocationRelativeTo(null);
        jw.setSize(500, 100);

    }

    public XorStateChanger () {
        initialState = null;
    }

    public JPanel getPanel() {
        JPanel toReturn = new JPanel (new GridLayout (3,1));
        
        toReturn.add (firstOperandsDisplay = new JLabel (initialState.getBv0().toBinaryString()));
        toReturn.add (secondOperandsDisplay = new JLabel (initialState.getBv1().toBinaryString()));
        toReturn.add (resultDisplay = new JLabel (initialState.getResult().toBinaryString()));

        firstOperandsDisplay.setHorizontalAlignment(JLabel.RIGHT);
        secondOperandsDisplay.setHorizontalAlignment(JLabel.RIGHT);
        resultDisplay.setHorizontalAlignment(JLabel.RIGHT);
        toReturn.setBorder(new BevelBorder (BevelBorder.RAISED));

        return toReturn;

    }

    private void setNew () {
        firstOperandsDisplay.setText (initialState.getBv0().toBinaryString());
        firstOperandsDisplay.paintImmediately(firstOperandsDisplay.getBounds());
        secondOperandsDisplay.setText (initialState.getBv1().toBinaryString());
        secondOperandsDisplay.paintImmediately(firstOperandsDisplay.getBounds());
        resultDisplay.setText (initialState.getResult().toBinaryString());
        resultDisplay.paintImmediately(firstOperandsDisplay.getBounds());

    }


    public void run() {
        int delay = ((Integer)GlobalPropertyRegistry.getGlobalPropertyRegistry().getProperty("animationSpeed")) * 100;

        jw.setVisible(true);
        Xor xor = new Xor();
        try {
            initialState.setInverseIndex(initialState.getSize()- 1);
            setNew ();
            
            Thread.sleep(delay);
            
            initialState.setResult(xor.apply(initialState.getBv0(), initialState.getBv1()));

            setNew ();
            Thread.sleep(delay);
        } catch (InterruptedException ie) {
            System.err.println ("ERRRRRR");
        }
    }

    public void close () {
        jw.dispose ();
    }
}
